# -*- coding: utf-8 -*-

"""
    Plugin for streaming video content from Reshet.ynet
"""

import urllib,urllib2,re,xbmcplugin,xbmcgui,os

##General vars
__plugin__ = "reshet"
__author__ = "Shmulik"


def CATEGORIES():
  
  matches = getMatches('http://reshet.ynet.co.il/Video/.aspx?fullChapterMore=1',"\['sId','(\d+)'\],\['Text','.*?'\],\['BoneName','(.*?)'\]")
  for id,name in matches:
      addDir(name,id,1,'DefaultFolder.png')
  matches = getMatches("http://reshet.ynet.co.il/Handlers/Dynamic/VideoGalleryTreeNodes.ashx?boneid=1","""<Node BoneName="(.*?)" Text=.*?style='white-space: nowrap'&gt;\(\d+\)&lt;/nobr&gt; " sId="(\d+)""""")
  for name,id in matches:
      addDir(name,id,1,'DefaultFolder.png')
  xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')

def getMatches(url,pattern):
  req = urllib2.Request(url)
  req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
  response = urllib2.urlopen(req)
  data=response.read().replace("\n","").replace("\t","").replace("\r","")
  response.close()
  matches=re.compile(pattern).findall(data)
  return matches
                       
def INDEX(url):

        founded = 1
        i=1
        allMatches=[]
        while founded != 0:
          purl = "http://reshet.ynet.co.il//PageHandlers/VideoGallery/videoGalleryPaging.aspx?orderId=order2&orderDirection=asc&isFullChapter=1&bId="+url+"&pageNum="+str(i)
          print("look in: "+purl)
          i=i+1
          matches = getMatches(purl,"""<a class="hand"><img align ="" class="ThumbClass"  rel=""  flvurl='(.*?)' src="(.*?)" width="140" height="80" border="" name="" title=".*?" alt=".*?"  ></a> +<span class="imgHoverImgHolder"></span> +</div> +<div class="caption"> +<h5><a>(.*?)</a></h5>.*?<span   class="episode">(.*?)</span> +<span class='duration'>\((.*?)\)</span>""")
          founded = len(matches)
          allMatches+=matches
        for url,pic,sub,name,dur in allMatches:
            addLink(clean(name),url,pic,dur,sub)
        xbmcplugin.addSortMethod(int(sys.argv[1]),xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(int(sys.argv[1]),xbmcplugin.SORT_METHOD_LABEL)
        xbmcplugin.addSortMethod(int(sys.argv[1]),xbmcplugin.SORT_METHOD_UNSORTED)
        xbmcplugin.addSortMethod(int(sys.argv[1]),xbmcplugin.SORT_METHOD_DURATION)
        xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
        
def clean(s):
  return re.sub('\s+', ' ', s)
                
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:	
                                param[splitparams[0]]=splitparams[1]
                                
        return param




def addLink(name,url,iconimage,time,sub):
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name,"Duration":time,"Tagline": sub} )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
        return ok


def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
        
              
params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

if mode==None or url==None or len(url)<1:
        CATEGORIES()
       
elif mode==1:
        INDEX(url)


xbmcplugin.setPluginFanart(int(sys.argv[1]),xbmc.translatePath( os.path.join( os.getcwd(),"fanart.jpg") ))
xbmcplugin.endOfDirectory(int(sys.argv[1]),cacheToDisc=True)
